from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
import re

from celery_tasks.email.tasks import send_verify_email
from goods.models import SKU
from users.models import User, Address


class CreateUserSerializer(serializers.ModelSerializer):

    password2 = serializers.CharField(label='确认密码', write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)  # true
    token = serializers.CharField(label='token', read_only=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'password', 'password2', 'mobile', 'sms_code', 'allow', 'token']
        extra_kwargs = {
            'username': {
                "min_length": 2,
                "max_length": 20,
                "error_messages": {  # 自定义校验出错的错误信息提示
                    "min_length": '仅允许2-20个字符的用户名',
                    "max_length": '仅允许2-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                "min_length": 8,
                "max_length": 20,
                "error_messages": {
                    "min_length": '仅允许8-20个字符的密码',
                    "max_length": '仅允许8-20个字符的密码',
                }
            }
        }

    def validate_mobile(self, value):
        """单独校验手机号"""
        if not re.match(r'1[1-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式有误')
        return value

    def validate_allow(self, value):
        """是否同意协议"""
        if value != 'true':
            raise serializers.ValidationError('请同意用户协议')
        return value

    def validate(self, attrs):
        """校验两个密码是否一样"""
        if attrs['password'] != attrs.get('password2'):
            raise serializers.ValidationError('两次密码不一致')

        # 校验验证码
        redis_conn = get_redis_connection('verify_codes')
        mobile = attrs.get('mobile')
        real_sms_code = redis_conn.get('sms_%s' % mobile)

        if real_sms_code is None or attrs.get('sms_code') != real_sms_code.decode():
            raise serializers.ValidationError('验证码以失效或验证码不正确')
        return attrs

    def create(self, validated_data):
        """移除不需要存储的数据"""
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        user = User.objects.create_user(**validated_data)
        # password = validated_data.pop('password')
        #
        # # user = User.objects.create(**validated_data)
        # user = super().create(validated_data)
        # user.set_password(password)
        # user.save()
        #

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        user.token = token

        return user


class UserDetailSerializer(serializers.ModelSerializer):
    """用户详情序列化器"""

    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'email', 'email_active']


class EmailSerializer(serializers.ModelSerializer):
    """更新邮箱序列化器"""
    class Meta:
        model = User
        fields = ['id', 'email']
        extra_kwargs = {
            'id': {
                "read_only": True
            },
            'email': {
                'required': True
            }
        }

    def update(self, instance, validated_data):
        """重写此方法的目的不是为了修改,而是借用此时机,发激活邮箱"""
        instance.email = validated_data.get('email')
        instance.save()

        verify_url = instance.generate_email_verify_url()
        print(verify_url)
        send_verify_email.delay(instance.email, verify_url=verify_url)
        return instance


class UserAddressSerializer(serializers.ModelSerializer):
    """
    用户收货地址序列化器
    """
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ['user', 'is_deleted', 'create_time', 'update_time']

    def validate_mobile(self, value):
        """
        验证手机号
        """
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError("手机号格式错误")
        return value

    def create(self, validated_data):
        validated_data['user'] = self.context.get('request').user
        return super().create(validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    修改标题
    """

    class Meta:
        model = Address
        fields = ['title', ]


class UserBrowserHistorySerializer(serializers.Serializer):
    """前端传的id是sku_id,保存商品浏览记录的序列化器"""

    sku_id = serializers.IntegerField(label='商品id', min_value=1)

    def validate_slu_id(self, value):
        """单独对sku_id进行校验"""
        try:
            SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('模型不存在')
        return value

    def create(self, validated_data):
        sku_id = validated_data.get('sku_id')
        # 获取当前的用户模型对象
        user = self.context.get('request').user
        # 将浏览记录存到Redis里
        # 创建Redis连接对象
        redis_conn = get_redis_connection('history')
        # 创建Redis管道
        pl = redis_conn.pipeline()
        # 先去重
        pl.lrem('history_%s' % user.id, 0, sku_id)
        # 再添加到列表的开头
        pl.lpush('history_%s' % user.id, sku_id)

        # 再截取列表中的5个元素
        pl.ltrim('history_%s' % user.id, 0, 4)
        pl.execute()
        return validated_data


class SKUSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKU
        fields = ['id', 'name', 'price', 'default_image_url', 'comments']
